package danran.dbapi.plugin;


import danran.dbapi.plugin.loader.PluginClassLoader;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class PluginManager {

    private static Map<String, CachePlugin> cachePlugins = new ConcurrentHashMap<>();
    private static Map<String, TransformerPlugin> transformPlugins = new ConcurrentHashMap<>();
    private static PluginClassLoader loader = new PluginClassLoader(PluginConf.getKey("plugin.targetPath"));

    public static CachePlugin getCachePlugin(String className) {
        if (cachePlugins.containsKey(className)) {
            return cachePlugins.get(className);
        } else {
            // 根据全类名通过反射的方式构建插件的实例对象
            try {
                Class clazz = Class.forName(className);
                CachePlugin plugin = (CachePlugin) clazz.newInstance();
                // 执行缓存插件的init方法
                plugin.init();
                // 添加到map中
                cachePlugins.put(className, plugin);
                return cachePlugins.get(className);
            } catch (Exception e) {
                throw new RuntimeException("get cache plugin failed: " + className);
            }
        }
    }

    public static TransformerPlugin getTransformPlugin(String className) {
        if (transformPlugins.containsKey(className)) {
            return transformPlugins.get(className);
        } else {
            try {
//                Class clazz = Class.forName(className);
                Class<?> clazz = loader.loadClass(className);
                TransformerPlugin plugin = (TransformerPlugin) clazz.newInstance();
                transformPlugins.put(className, plugin);
                return transformPlugins.get(className);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("get transform plugin failed: " + className + "=>with Exception:" + e.getMessage());
            }
        }
    }
}
